package com.xli.security.sensitive.processor;

import com.xli.security.sensitive.annotation.SensitiveField;
import com.xli.security.sensitive.type.SensitiveTypeHandler;
import com.xli.security.sensitive.type.SensitiveTypeRegistry;

import java.lang.reflect.Field;

public class SensitiveProcessor {

    public static <T> T processSensitiveFields(T vo) {
        try {
            if (vo == null) {
                return null;
            }

            // 遍历 VO 类的字段
            for (Field field : vo.getClass().getDeclaredFields()) {
                if (field.isAnnotationPresent(SensitiveField.class)) {
                    field.setAccessible(true);
                    SensitiveField sensitive = field.getAnnotation(SensitiveField.class);
                    SensitiveTypeHandler handler = SensitiveTypeRegistry.get(sensitive.value());

                    // 获取字段值并进行脱敏处理
                    Object value = field.get(vo);
                    if (value != null) {
                        field.set(vo, handler.handle(value));  // 设置脱敏后的值
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Error processing sensitive fields", e);
        }
        return vo;
    }
}
